﻿using System.Net.Sockets;
using System.Net;
using System.Text;
using System;

namespace Telnet
{
    public class TelnetClass
    {
        private Socket client = new Socket(AddressFamily.InterNetwork, 
            SocketType.Stream, ProtocolType.Tcp);

        public bool gotPrompt = false;

        public TelnetClass(string Remote)
        {
            client.BeginConnect(new IPEndPoint(IPAddress.Parse(Remote), 23), new AsyncCallback(OnConnect), null);
        }

        public void OnConnect(IAsyncResult ar)
        {
            client.EndConnect(ar);
        }

        public void Close()
        {
            client.Close();
        }

        public void SendCmd(string cmd)
        {
            System.Threading.Thread.Sleep(500);
            cmd += "\n";
            client.Send(Encoding.ASCII.GetBytes(cmd));
        }

        public void Login(string usr, string pass)
        {
            SendCmd(usr);
            SendCmd(pass);
            gotPrompt = GetPrompt();
        }

        private bool GetPrompt()
        {
            byte[] byteData = new byte[1024];
            SendCmd("");
            System.Threading.Thread.Sleep(500);
            client.Receive(byteData, 0, byteData.Length,
                    SocketFlags.None);
            string s = Encoding.ASCII.GetString(byteData);
            char[] prompt = { '$', '>' };
            int p = s.IndexOfAny(prompt);
            if (p > 0)
                return true;
            return false;
        }
    }
}
